package muilty_thread.java_current_practice_and_kernel.cp5;

import java.util.concurrent.CountDownLatch;

public class TestHarness {
    public long timeTasks(int nThreads, final Runnable task) throws InterruptedException {
        final CountDownLatch startGate = new CountDownLatch(1);
        final CountDownLatch endGate = new CountDownLatch(nThreads);
        for (int i = 0; i < nThreads; i++) {
            new Thread(() -> {
                try {
                    startGate.await();
                    try{
                        task.run();
                    }finally {
                        endGate.countDown();
                    }

                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }

            }).start();
        }
        long start = System.nanoTime();
        startGate.countDown();
        endGate.await();
        long end = System.nanoTime();

        return end - start;


    }

    public static void main(String[] args) throws InterruptedException {
        TestHarness th = new TestHarness();
        long l = th.timeTasks(10, th::doSth);
        System.out.println(l);
    }
    public void doSth(){
        System.out.println("do something");

    }


}
